import {
  login,
  getUserInfo,
  getUserDetail
} from '@/api/user'
import { setToken,
  getToken,
  removeToken,
  setTimeStamp } from '@/utils/auth'

const state = {
  // token: localStorage.getItem('token')
  token: getToken('token'),
  userInfo: {}
}
const mutations = {
  setToken(state, data) {
    // console.log(data)
    state.token = data
    // console.log(12)
    // console.log(getToken('token'))
    setToken(data)
    setTimeStamp()
    // 存储在本地localStorage
    // localStorage.setItem('token', data)
  },
  removeToken(state) {
    state.token = ''
  },
  setUserInfo(state, data) {
    state.userInfo = { ...data }
    console.log(state.userInfo)
  },
  removeUserInfo(state) {
    state.userInfo = {}
    removeToken()
  }
}
const actions = {
  // login(store, data) {
  //   login(data).then(res => {
  //     console.log(res)
  //     store.commit('setToken', res.data.data)
  //   }).catch(err => console.log(err))
  // }
  async login(store, data) {
    const res = await login(data)
    // console.log(res)
    // 判断返回数据是否正确
    // if (res.data.success) {
    //   store.commit('setToken', res.data.data)
    // }
    // 响应处理后返回的数据，现在的res进士token
    if (res) {
      store.commit('setToken', res)
      // console.log(res)
    }
  },
  async getUserInfoW(store) {
    // console.log(123)
    const res = await getUserInfo()
    console.log(res.userId)
    const userDetail = await getUserDetail(res.userId)
    // console.log(userDetail)
    const data = {
      ...res,
      ...userDetail
    }
    store.commit('setUserInfo', data)
  },
  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }

}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
